﻿using System;
using System.Linq;
using System.Text;
using Foothill.Common;

namespace Foothill.Service.AdService
{
    public static class SecurityUtility
    {
        private static readonly int _PostIdOffset = 100000;
        
        private static readonly string _EditKeyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        // generate a random password of speficied length
        public static string GenerateRandomPassword(int length)
        {
            int size = _EditKeyChars.Length;
            StringBuilder sb = new StringBuilder();
            Random rand = new Random();

            int index = 0;

            for(int i=0; i< length; ++i)
            {
                index = rand.Next(0, size);
                sb.Append(_EditKeyChars[index]);
            }

            return sb.ToString();
        }

        public static int MaskEditPostId(int unmaskedId)
        {
            return unmaskedId + _PostIdOffset;
        }

        public static int UnmaskEditPostId(int postIdFromQueryParam)
        {
            return postIdFromQueryParam - _PostIdOffset;
        }

        public static bool IsValidPostId(string postIdStr, out int maskedpostId)
        {
            maskedpostId = 0;

            if (Int32.TryParse(postIdStr, out maskedpostId))
            {
                return maskedpostId > _PostIdOffset;
            }
            else
            {
                return false;
            }
        }

        public static bool IsValidPostId(int maskedPostId)
        {
            return maskedPostId > _PostIdOffset;
        }

        public static bool IsValidEditKey(string editKey)
        {
            if (GlobalSettings.EditKeyLength != editKey.Length)
            {
                return false;
            }

            char[] temp = editKey.ToCharArray();

            for (int i = 0; i < GlobalSettings.EditKeyLength; ++i)
            {
                if (!_EditKeyChars.Contains(temp[i]))
                {
                    return false;
                }
            }

            return true;
        }
    }
}
